<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.ruleForm.id ? '编辑' : '添加'" v-model="state.dialog.isShowDialog" width="769px" :before-close="closeDialog">
			<el-form ref="dialogFormRef" :model="state.ruleForm" size="default" label-width="90px" :rules="rules">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="角色名称" prop="name">
							<el-input v-model="state.ruleForm.name" placeholder="请输入角色名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="角色描述" prop="description">
							<el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入角色描述" maxlength="150"></el-input>
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单权限">
							<el-tree ref="elTreeRef" :data="state.menuData" :props="state.menuProps" node-key="id" show-checkbox check-strictly class="menu-data-tree"/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemRoleDialog">
// 后台接口
import { systemApi } from '/@/api/system/index';
// 表单验证
const rules = reactive({
	name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
});

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const dialogFormRef = ref();
const elTreeRef = ref();
const state = reactive({
	ruleForm: {
		id: '',
		name: '', // 角色名称
		description: '', // 角色描述
    checkedList: [],  //菜单权限，选中节点
    createBy: '' //操作用户id
	},
	menuData: [] as TreeType[],
	menuProps: {
		children: 'children',
		label: 'label',
	},
	dialog: {
		isShowDialog: false,
		type: '',
	},
});

// 打开弹窗
const openDialog = (type: string, row: RowRoleType) => {
  state.dialog.isShowDialog = true;
  nextTick(async () => {
    dialogFormRef.value.resetFields();  // 清空表单并移除校验结果，此项需加表单验证才能使用
    if (type === 'edit') {
      state.ruleForm = JSON.parse(JSON.stringify(row));
			// 菜单权限-默认选中设置
			let res = await systemApi().getMenuRole({
				id: row.id
			})
			const defaultCheckedKeys = res.datas.map((item: any) => item.menuid)
			nextTick(()=>{
				elTreeRef.value.setCheckedKeys(defaultCheckedKeys);
			})
    }else{
			state.ruleForm = {
				id: '',
				name: '', // 角色名称
				description: '', // 角色描述
				checkedList: [],  //菜单权限，选中节点
				createBy: '' //操作用户id
			}
		}
  })
};
// 关闭弹窗
const closeDialog = () => {
	elTreeRef.value.setCheckedKeys([]);
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = async () => {
  // 表单验证
  await dialogFormRef.value?.validate(async (valid: Boolean) => {
    if (valid) {
      let checkedList = elTreeRef.value.getCheckedNodes(false, true);
      if(checkedList.length){
        // 保存到数据库
        // state.ruleForm.createBy = store.state.userInfos.userInfos.id; //操作用户id
        state.ruleForm.checkedList = checkedList;
        let res: any = await systemApi().addRole(state.ruleForm);
        if (res.success) {
          emit('refresh')
          ElMessage.success(state.ruleForm.id ? '编辑成功' : '添加成功');
        } else {
          ElMessage.error(state.ruleForm.id ? '编辑失败' : '添加失败');
        }
        closeDialog();
      }else{
        ElMessage.warning('请勾选菜单权限！');
      }
    }
  });
};
// 获取菜单结构数据
const getMenuData = async () => {
  let res = await systemApi().getMenuList();
  state.menuData = res.datas;
};

// 页面加载时
onMounted(() => {
  getMenuData();
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.system-role-dialog-container {
	.menu-data-tree {
		width: 100%;
		border: 1px solid var(--el-border-color);
		border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
		padding: 5px;
	}
}
</style>
